<template>
  <el-dialog :title="title" :model-value="visible" width="900px" @close="$emit('close')">
    <div class="image-manager">
      <!-- 现有图片展示区域 -->
      <div class="existing-images" v-if="existingImages.length > 0">
        <h4>现有图片</h4>
        
        <!-- 商品列表页展示图 -->
        <div class="image-category-display" v-if="listImages.length > 0">
          <h5>商品列表页展示图</h5>
          <div class="image-grid">
            <div
              v-for="image in listImages"
              :key="image.imageId"
              class="image-item list-image"
              :class="{ 'is-main': image.isMain === 1 }"
            >
              <div class="image-wrapper">
                <img :src="getImageUrl(image.imageUrl)" :alt="image.imageName" />
                <div class="image-overlay">
                  <el-button
                    size="small"
                    type="primary"
                    v-if="image.isMain !== 1"
                    @click="setMainImage(image.imageId)"
                  >
                    设为主图
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteImage(image.imageId)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
              <div class="image-info">
                <span class="image-name">{{ image.imageName }}</span>
                <span class="image-type-badge list-badge">列表页展示图</span>
                <span v-if="image.isMain === 1" class="main-badge">主图</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 商品详细页细节图 -->
        <div class="image-category-display" v-if="detailImages.length > 0">
          <h5>商品详细页细节图</h5>
          <div class="image-grid">
            <div
              v-for="image in detailImages"
              :key="image.imageId"
              class="image-item detail-image"
              :class="{ 'is-main': image.isMain === 1 }"
            >
              <div class="image-wrapper">
                <img :src="getImageUrl(image.imageUrl)" :alt="image.imageName" />
                <div class="image-overlay">
                  <el-button
                    size="small"
                    type="primary"
                    v-if="image.isMain !== 1"
                    @click="setMainImage(image.imageId)"
                  >
                    设为主图
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteImage(image.imageId)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
              <div class="image-info">
                <span class="image-name">{{ image.imageName }}</span>
                <span class="image-type-badge detail-badge">详细页细节图</span>
                <span v-if="image.isMain === 1" class="main-badge">主图</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他类型图片 -->
        <div class="image-category-display" v-if="otherImages.length > 0">
          <h5>商品列表图片</h5>
          <div class="image-grid">
            <div
              v-for="image in otherImages"
              :key="image.imageId"
              class="image-item"
              :class="{ 'is-main': image.isMain === 1 }"
            >
              <div class="image-wrapper">
                <img :src="getImageUrl(image.imageUrl)" :alt="image.imageName" />
                <div class="image-overlay">
                  <el-button
                    size="small"
                    type="primary"
                    v-if="image.isMain !== 1"
                    @click="setMainImage(image.imageId)"
                  >
                    设为主图
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteImage(image.imageId)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
              <div class="image-info">
                <span class="image-name">{{ image.imageName }}</span>
                <span class="image-type">{{ image.imageType }}</span>
                <span v-if="image.isMain === 1" class="main-badge">主图</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 上传新图片区域 -->
      <div class="upload-section">
        <h4>上传新图片</h4>
        
        <!-- 商品列表页展示图上传 -->
        <div class="upload-category">
          <h5>商品列表页展示图（单个图片）</h5>
          <el-upload
            action="#"
            :http-request="(options) => doUpload(options, 'list')"
            list-type="picture-card"
            :file-list="listImageFiles"
            :on-remove="(file) => handleRemove(file, 'list')"
            :on-success="handleSuccess"
            :auto-upload="true"
            :limit="1"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tips">
            <p>用于商品列表页显示的主图，只能上传1张</p>
          </div>
        </div>

        <!-- 商品详细页细节图上传 -->
        <div class="upload-category">
          <h5>商品详细页细节图（多个图片）</h5>
          <el-upload
            action="#"
            :http-request="(options) => doUpload(options, 'detail')"
            list-type="picture-card"
            :file-list="detailImageFiles"
            :on-remove="(file) => handleRemove(file, 'detail')"
            :on-success="handleSuccess"
            :auto-upload="true"
            multiple
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tips">
            <p>用于商品详细页显示的细节图，可以上传多张</p>
            <p>支持格式：JPEG、PNG、GIF、WebP</p>
            <p>单文件最大：10MB</p>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="$emit('close')">关闭</el-button>
      <el-button type="primary" @click="refreshImages">刷新图片列表</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile, UploadRequestOptions } from 'element-plus'
import { productService } from '@/api'
import type { ProductImage } from '@/types'

const props = defineProps<{
  visible: boolean
  title?: string
  shoeId: number
}>()

const emit = defineEmits<{ (e: 'close'): void; (e: 'uploaded'): void }>()

const fileList = ref<UploadFile[]>([])
const listImageFiles = ref<UploadFile[]>([])
const detailImageFiles = ref<UploadFile[]>([])
const existingImages = ref<ProductImage[]>([])
const loading = ref(false)

// 计算属性：根据图片类型分类现有图片
const listImages = computed(() => {
  return existingImages.value.filter(image => image.imageType === 'list')
})

const detailImages = computed(() => {
  return existingImages.value.filter(image => image.imageType === 'detail')
})

const otherImages = computed(() => {
  return existingImages.value.filter(image => image.imageType !== 'list' && image.imageType !== 'detail')
})

// 监听弹窗显示状态，显示时加载图片
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      loadExistingImages()
    }
  }
)

// 加载现有图片
const loadExistingImages = async () => {
  if (!props.shoeId) return
  
  loading.value = true
  try {
    const response = await productService.getShoesImages(props.shoeId)
    console.log('API响应:', response)
    console.log('响应数据结构:', response.data)
    
    // 处理标准的ApiResponse格式：{ code, msg, data, error, ok }
    let imageData = []
    if (response.data && response.data.data && Array.isArray(response.data.data)) {
      imageData = response.data.data
    } else if (response.data && Array.isArray(response.data)) {
      imageData = response.data
    }
    
    existingImages.value = imageData
    console.log('加载的图片数据:', existingImages.value)
    console.log('图片数量:', imageData.length)
  } catch (error) {
    console.error('获取图片列表失败:', error)
    ElMessage.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 获取图片完整URL
const getImageUrl = (imageUrl: string) => {
  if (!imageUrl) {
    console.log('图片URL为空')
    return ''
  }
  
  // 如果已经是完整URL，直接返回
  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
    console.log('使用完整URL:', imageUrl)
    return imageUrl
  }
  
  // 如果是相对路径，添加API基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8083'
  const fullUrl = baseUrl + imageUrl
  console.log('构建图片URL:', imageUrl, '->', fullUrl)
  return fullUrl
}

// 上传图片
const doUpload = async (options: UploadRequestOptions, imageType: 'list' | 'detail' = 'detail') => {
  const { file, onSuccess, onError } = options
  
  try {
    let response
    if (imageType === 'list') {
      // 上传商品列表页展示图（单个图片，设为主图）
      response = await productService.uploadShoesImage(props.shoeId, file, 'list', true)
      ElMessage.success('商品列表页展示图上传成功')
    } else {
      // 上传商品详细页细节图（多个图片，不设为主图）
      response = await productService.uploadShoesImage(props.shoeId, file, 'detail', false)
      ElMessage.success('商品详细页细节图上传成功')
    }
    
    onSuccess(response.data)
    
    // 刷新图片列表
    await loadExistingImages()
    emit('uploaded')
  } catch (error: unknown) {
    console.error('上传失败:', error)
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    
    // 创建符合Element Plus错误类型的对象
    const uploadError = {
      status: 500,
      method: 'POST',
      url: '',
      message: errorMessage,
      name: 'UploadError'
    }
    
    onError(uploadError)
    ElMessage.error(`上传失败: ${errorMessage}`)
  }
}

// 删除图片
const deleteImage = async (imageId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await productService.deleteShoesImage(props.shoeId, imageId)
    ElMessage.success('图片删除成功')
    
    // 刷新图片列表
    await loadExistingImages()
    emit('uploaded')
  } catch (error: unknown) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      ElMessage.error(`删除失败: ${errorMessage}`)
    }
  }
}

// 设置主图
const setMainImage = async (imageId: number) => {
  try {
    await productService.setShoesMainImage(props.shoeId, imageId)
    ElMessage.success('设置主图成功')
    
    // 刷新图片列表
    await loadExistingImages()
    emit('uploaded')
  } catch (error: unknown) {
    console.error('设置主图失败:', error)
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    ElMessage.error(`设置主图失败: ${errorMessage}`)
  }
}

// 移除上传文件
const handleRemove = (file: UploadFile, imageType?: 'list' | 'detail') => {
  if (imageType === 'list') {
    // 从列表页图片文件列表中移除
    const index = listImageFiles.value.findIndex(f => f.uid === file.uid)
    if (index > -1) {
      listImageFiles.value.splice(index, 1)
    }
  } else if (imageType === 'detail') {
    // 从详细页图片文件列表中移除
    const index = detailImageFiles.value.findIndex(f => f.uid === file.uid)
    if (index > -1) {
      detailImageFiles.value.splice(index, 1)
    }
  } else {
    // 兼容原有逻辑
    const index = fileList.value.findIndex(f => f.uid === file.uid)
    if (index > -1) {
      fileList.value.splice(index, 1)
    }
  }
}

// 上传成功
const handleSuccess = () => {
  // 上传成功后，文件会自动添加到fileList中
  // 这里可以添加额外的成功处理逻辑
}

// 刷新图片列表
const refreshImages = async () => {
  await loadExistingImages()
}

// 组件挂载时加载图片
onMounted(() => {
  loadExistingImages()
})
</script>

<style scoped>
.image-manager {
  max-height: 600px;
  overflow-y: auto;
}

.existing-images {
  margin-bottom: 30px;
}

.existing-images h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.image-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  
  transition: all 0.3s;
}

.image-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.image-item.is-main {
  border-color: #67c23a;
  border-width: 2px;
}

.image-wrapper {
  position: relative;
  height: 150px;
  
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-info {
  padding: 10px;
  background: #f8f9fa;
}

.image-name {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-type {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.main-badge {
  display: inline-block;
  background: #67c23a;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.upload-section {
  border-top: 1px solid #e4e7ed;
  padding-top: 20px;
}

.upload-section h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.upload-category {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
}

.upload-category h5 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.image-category-display {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #f9f9f9;
}

.image-category-display h5 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.image-type-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 8px;
}

.list-badge {
  background-color: #e1f3d8;
  color: #67c23a;
  border: 1px solid #b3d8a4;
}

.detail-badge {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

.list-image {
  border: 2px solid #67c23a;
}

.detail-image {
  border: 2px solid #409eff;
}

.upload-tips {
  margin-top: 15px;
  color: #666;
  font-size: 12px;
}

.upload-tips p {
  margin: 2px 0;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
</style>
